package com.erlinyou.im.web.wshandler;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.WebSocketSession;

import com.erlinyou.travel.web.controller.user.LoginController;

/**
 * web socket session 管理
 * 
 * @author Administrator
 *
 */
public class WSSManager {
	/**
	 * 全局的session 存储
	 */
	private static final Map<Long, Map<String,LocalWebSocketSession>> sessions = new HashMap<>();
	private static Logger logger = LoggerFactory.getLogger(WSSManager.class);
	
	
	public static LocalWebSocketSession addSession(Long userid,LocalWebSocketSession session){
		Map<String, LocalWebSocketSession> sessionMap = sessions.get(userid);
		if(sessionMap == null){
			sessionMap = new HashMap<>();
			sessions.put(userid, sessionMap);
		}
		return sessionMap.put(session.getId(), session);
	}
	
	public static void removeSession(Long userid,WebSocketSession webSocketSession){
		Map<String, LocalWebSocketSession> sessionMap = sessions.get(userid);
		if(sessionMap != null){
			sessionMap.remove(webSocketSession.getId());
			if(sessionMap.size() == 0){
				sessions.remove(userid);
			}
		}
	}
	
	public static Map<String,LocalWebSocketSession> getSession(Long userid){
		return sessions.get(userid);
	}
	
	
	/**
	 * 推送消息给在线用户
	 * @param userid
	 * @param pushContent
	 * @throws IOException
	 */
	public static void sendMessageText(Long userid, String pushContent) throws IOException {
		Map<String, LocalWebSocketSession> session = WSSManager.getSession(userid);
		if(session != null){
			Collection<LocalWebSocketSession> values = session.values();
			for (LocalWebSocketSession webSocketSession : values) {
				webSocketSession.sendLocalMessage(pushContent);
			}
		}
	}
	/**
	 * 推送消息给多个在线用户
	 * @param toUserids
	 * @param pushContent
	 * @throws IOException
	 */
	public static void sendMessageText(List<Long> toUserids, String pushContent) throws IOException {
		for (Long toUserid : toUserids) {
			
			sendMessageText(toUserid, pushContent);
		}
	}
}
